﻿#!/usr/bin/python
#-*- coding:utf-8 -*-


import hashlib as hasher
import datetime as date
# 首先定义我们的区块连将会是什么样子,有哪些功能
class Block:
	def __init__(self,index,timestamp,data,previous_hash):
		self.index = index
		self.timestamp = timestamp
		self.data = data
		self.previous_hash = previous_hash
		self.hash = self.hash_block()
		
	def hash_block(self):
		# 用sha256进行加密
		sha = hasher.sha256()
		sha.update((str(self.index)+str(self.timestamp)+str(self.data)+str(self.previous_hash)).encode('utf-8'))
		return sha.hexdigest()

		
def create_genesis_block():
	# 手动构造块链,索引为0或者任意先前块链的散列
	return Block(0,date.datetime.now(),'Genesis block','0')

#起源块后续的块链都会以何种方式陆续创建,怎么去创建
def next_block(last_block):
	this_index = last_block.index + 1
	this_timestamp = date.datetime.now()
	this_data = 'hey 我是区块链:' + str(this_index)
	this_hash = last_block.hash
	return Block(this_index,this_timestamp,this_data,this_hash)

#创建块链并添加起源块
blockchain = [create_genesis_block()]
previous_block = blockchain[0]

num_of_block_to_add = 20

for i in range(0,num_of_block_to_add):
	block_to_add = next_block(previous_block)
	blockchain.append(block_to_add)
	previous_block = block_to_add
	print('%d' % (block_to_add.index))
	print('hash:%s\nlen:%d\ndata:%s\ndate:%s\n' % (block_to_add.hash,len(block_to_add.hash),block_to_add.data,block_to_add.timestamp))
	
	
	